
package controllers;
import dataaccess.BaseDao;
import play.*;
import play.mvc.*;
import dataaccess.ProjectDataAccess;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import model.Users;
import views.html.*;
import play.db.jpa.Transactional;
import play.data.*;
import static play.data.Form.*;

/**
 *
 * @author overflow012
 */
public class Usuarios extends Controller{
    
    public static class Login {
        
        public String email;
        public String password;
        
        public String validate() {
            if(Users.BuscarPorAutenticacion(email, password) == null) {
                return "Usuario o Contraseña invalidas";
            }
            return null;
        }
        
    }
    
    public static Result login() {
        return ok(
            userLogin.render(form(Usuarios.Login.class))
        );
    }
    
     public static Result loginAdmin() {
        return ok(
            adminLogin.render(form(Usuarios.Login.class))
        );
    }
    
    @play.db.jpa.Transactional
    public static Result autenticar() {
        DynamicForm loginForm = form().bindFromRequest();
        Logger.info("email: " + loginForm.get("email") + " pass: " + loginForm.get("password") );
        Users usuario = Users.BuscarPorAutenticacion(loginForm.get("email"), loginForm.get("password"));
        if(usuario != null){
            session("email", loginForm.get("email"));
            session("user_id", usuario.getUserId().toString());
            return redirect(
                routes.Tareas.listarTareas()
            );
      
        }
        return ok(userLogin.render(form(Usuarios.Login.class)));
    }
    
    
    @play.db.jpa.Transactional
    public static Result autenticarAdmin() {
        DynamicForm loginForm = form().bindFromRequest();
        Logger.info("email: " + loginForm.get("email") + " pass: " + loginForm.get("password") );
        Users usuario = Users.BuscarPorAutenticacion(loginForm.get("email"), loginForm.get("password"));
        if(usuario != null){
            session("email", loginForm.get("email"));
            session("id", usuario.getUserId().toString());
            return redirect(
                routes.Application.index()
            );
        }
        return ok(userLogin.render(form(Usuarios.Login.class)));
    }
    
    public static Result logout() {
        session().clear();
        flash("success", "Sesión Finalizada");
        return redirect(
            routes.Usuarios.login()
        );
    }
        
}
